package handle_client;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

public class FileDelegate extends Thread{
	private int user_number;
	private int sender_id;
	private Socket socket;
	private String filepath;
	
	public FileDelegate(int user_number, int sender_id,Socket socket,String filepath) {
		super();
		this.user_number = user_number;
		this.sender_id = sender_id;
		this.socket = socket;
		this.filepath = filepath;
	}

	@Override
	public void run() {
        File fi = new File(filepath);   
        try {
        
        		DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filepath)));        	
			DataOutputStream ps = new DataOutputStream(socket.getOutputStream());
			ps.writeUTF(fi.getName());
            ps.flush();
            ps.writeLong((long) fi.length());
            ps.flush();
            
            int bufferSize = 8192;
            byte[] buf = new byte[bufferSize];
            
            while (true) {
                int read = 0;
                if (fis != null) {
                    read = fis.read(buf);
                }

                if (read == -1) {
                    break;
                }
                ps.write(buf, 0, read);
            }
            ps.flush();
            
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		super.run();
	}
	
	
}
